import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common.Utils import BlogDriver


class BlogLogin:
    driver = ""
    url = ""

    def __init__(self):
        self.driver = BlogDriver.driver
        self.url = "http://8.137.19.140:9090/blog_login.html"
        self.driver.get(self.url)

    def BlogSucText(self):  # 成功登录博客页面
        # 输入正确的账号
        self.driver.find_element(By.CSS_SELECTOR, "#username").send_keys("zhangsan")
        # 输入正确的密码
        self.driver.find_element(By.CSS_SELECTOR, "#password").send_keys("123456")
        # 找到登录按钮并且点击
        self.driver.find_element(By.CSS_SELECTOR, "#submit").click()

        BlogDriver.GetScreenShot()
        # 进去后检查一下用户的昵称是否存在
        name = self.driver.find_element(By.CSS_SELECTOR, "body > div.container > div.left > div > h3").text
        # 用户基本信息的文章是否存在
        article = self.driver.find_element(By.CSS_SELECTOR, "body > div.container > div.left > div > div:nth-child(4) > span:nth-child(1)").text
        # 用户基本信息的分类是否存在
        classification = self.driver.find_element(By.CSS_SELECTOR, "body > div.container > div.left > div > div:nth-child(4) > span:nth-child(2)").text
        print("BlogLogin:"+name)

    # self.driver.quit()  #两个函数连用就得在登录失败的函数里面退出了

    def BlogFailText(self):  # 错误登录博客
        # 使用回退按钮，退回到登录页面
        self.driver.back()
        # 找到用户命名输入框和密码输入框把里面的内容清空
        self.driver.find_element(By.CSS_SELECTOR, "#username").clear()
        self.driver.find_element(By.CSS_SELECTOR, "#password").clear()
        # 然后再输入错误的账号或者错误的密码
        time.sleep(1)
        self.driver.find_element(By.CSS_SELECTOR, "#username").send_keys("lisi")
        self.driver.find_element(By.CSS_SELECTOR, "#password").send_keys("123")
        time.sleep(1)
        BlogDriver.GetScreenShot()
        self.driver.find_element(By.CSS_SELECTOR, "#submit").click()
        # 检查是否登录失败
        # 显示等待两秒
        wait = WebDriverWait(self.driver, 2)
        wait.until(EC.alert_is_present())
        alert = self.driver.switch_to.alert
        print(alert.text)
        assert alert.text == "密码错误"
        alert.accept()  # 点击同意按钮
